package org.hhh.order.service.impl;

import org.hhh.basic.constant.BaseConstants;
import org.hhh.basic.service.impl.BaseServiceImpl;
import org.hhh.basic.util.CodeGenerateUtils;
import org.hhh.basic.util.DistanceUtil;
import org.hhh.basic.util.PageList;
import org.hhh.basic.util.QuartzJobInfo;
import org.hhh.order.domain.OrderAddress;
import org.hhh.order.domain.ProductOrder;
import org.hhh.order.domain.ProductOrderDetail;
import org.hhh.order.mapper.OrderAddressMapper;
import org.hhh.order.mapper.ProductOrderDetailMapper;
import org.hhh.order.mapper.ProductOrderMapper;
import org.hhh.order.query.ProductOrderQuery;
import org.hhh.order.service.IProductOrderService;
import org.hhh.org.domain.Employee;
import org.hhh.org.domain.Shop;
import org.hhh.org.mapper.EmployeeMapper;
import org.hhh.org.mapper.ShopMapper;
import org.hhh.pay.constants.PayConstants;
import org.hhh.pay.domain.PayBill;
import org.hhh.pay.mapper.PayBillMapper;
import org.hhh.pay.service.IPayBillService;
import org.hhh.product.domain.Product;
import org.hhh.product.mapper.ProductMapper;
import org.hhh.quartz.service.IQuartzService;
import org.hhh.user.domain.Logininfo;
import org.hhh.user.domain.User;
import org.hhh.user.domain.UserAddress;
import org.hhh.user.mapper.UserAddressMapper;
import org.hhh.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.channels.Pipe;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class ProductOrderServiceImpl extends BaseServiceImpl<ProductOrder> implements IProductOrderService {
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ProductOrderMapper productOrderMapper;

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private OrderAddressMapper orderAddressMapper;

    @Autowired
    private PayBillMapper payBillMapper;

    @Autowired
    private IPayBillService payBillService;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private ProductOrderDetailMapper productOrderDetailMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private IQuartzService quartzService;

    @Override
    public String submit(Map<String, Object> params, Logininfo currentLogininfo) {
        //服务方式
        Long serviceMethod=Long.valueOf(params.get("service_method").toString());
        //服务地址
        Long addressId = Long.valueOf(params.get("address_id").toString());
        //支付方式
        Long payMethod = Long.valueOf(params.get("pay_method").toString()); // 0 支付宝 1 微信  2 银联
        //当前购买服务
        Long productId = Long.valueOf(params.get("product_id").toString());
        //销售数量
        Long amount = Long.valueOf(params.get("amount").toString());
        Product product = productMapper.loadById(productId);
        //绑定购买人
        User user = userMapper.loadByLogininfoId(currentLogininfo.getId());
        productMapper.upadate(product);
        //生成购买订单
        UserAddress address = userAddressMapper.loadById(addressId);
        ProductOrder order = initProductOrder(product,address,user);
        String paySn = CodeGenerateUtils.generateUnionPaySn();
        //统一支付标识订单
        order.setPaySn(paySn);
        //保存服务订单
        productOrderMapper.save(order);//订单返回自增id

        //保存服务订单详情表
        ProductOrderDetail productOrderDetail = initProductOrderDetail(product);
        productOrderDetail.setOrder_id(order.getId());
        productOrderDetailMapper.save(productOrderDetail);

        //保存订单服务地址
        OrderAddress orderAddress = initOrderAddress(order, address);
        orderAddressMapper.save(orderAddress);
        // 生成支付订单支付
        PayBill bill = initPayBill(payMethod, user, order);
        payBillMapper.save(bill);
        //添加定时任务
        QuartzJobInfo jobInfo = new QuartzJobInfo();
        jobInfo.setJobName(BaseConstants.PAY_TIMEOUT_CANCEL_PRODUCT + order.getId());//jobName
        Map<String,Object> map = new HashMap<>();
        map.put("type",BaseConstants.PAY_TIMEOUT_CANCEL_PRODUCT);
        map.put("orderId",order.getId());
        jobInfo.setParams(map);//参数
        jobInfo.setFireDate(order.getLastPayTime());//执行时间
        quartzService.addJob(jobInfo);

        //封装支付接口  响应数据包
        return payBillService.pay(bill);
        //@TODO 支付超时定时器
    }

    @Override
    public PageList<ProductOrder> admin(ProductOrderQuery query, Logininfo currentLogininfo) {
        Employee employee = employeeMapper.loadByLogininfoId(currentLogininfo.getId());
        if (employee.getShop_id()!=null){
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    @Override
    public PageList<ProductOrder> user(ProductOrderQuery query, Logininfo currentLogininfo) {
        User user = userMapper.loadByLogininfoId(currentLogininfo.getId());
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    @Override
    public void cancelOrderByQuartz(Long orderId) {
        ProductOrder order = productOrderMapper.loadById(orderId);
        if (order.getState()==0){
            //未支付
            order.setState(-1);
            productOrderMapper.upadate(order);
            System.out.println("15分未支付取消订单"+order.getId());
        }

    }

    private ProductOrderDetail initProductOrderDetail(Product product) {
        ProductOrderDetail productOrderDetail = new ProductOrderDetail();
        BeanUtils.copyProperties(product,productOrderDetail);
        return productOrderDetail;
    }


    private PayBill initPayBill(Long payMethod, User user, ProductOrder order) {
        PayBill bill = new PayBill();
        bill.setDigest("[摘要]对"+order.getDigest()+"支付订单！");
        bill.setMoney(order.getPrice());
        //统一支付标识
        bill.setUnionPaySn(order.getPaySn());
        bill.setLastPayTime(order.getLastPayTime());
        bill.setPayChannel(payMethod);
        //唯一业务键
        bill.setBusinessType(PayConstants.FUWU_ORDER);
        bill.setBusinessKey(order.getId());
        bill.setUser_id(order.getUser_id());
        bill.setShop_id(order.getShop_id());
        bill.setNickName(user.getUsername());
        return bill;
    }

    private OrderAddress initOrderAddress(ProductOrder order, UserAddress address) {
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(address, orderAddress);
        orderAddress.setOrder_id(order.getId());
        orderAddress.setOrderSn(order.getOrderSn());
        return orderAddress;
    }

    private ProductOrder initProductOrder(Product product,UserAddress address, User user) {
        ProductOrder order = new ProductOrder();
        order.setDigest("[摘要]对"+product.getName()+"购买订单！");
        order.setState(0);//待支付
        order.setPrice(product.getSaleprice());//售价
        String orderSn = CodeGenerateUtils.generateOrderSn(user.getId());//订单编号
        order.setOrderSn(orderSn);
        order.setProduct_id(product.getId());
        order.setUser_id(user.getId());
        Shop nearestShop = DistanceUtil.getNearestShop(DistanceUtil.getPoint(address.getFullAddress()), shopMapper.loadAll());
        order.setShop_id(nearestShop.getId());
        order.setLastPayTime(new Date(System.currentTimeMillis()+1*60*1000));//最后支付时间
        return order;
    }
}
